package org.example.Server.service.homework;

import lombok.extern.slf4j.Slf4j;
import org.example.Server.mapper.homework.TeacherHomeworkMapper;
import org.example.Server.model.homework.*;
import org.example.Server.utils.ResultAPI;
import org.example.Server.utils.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static org.example.Server.utils.ExceptionEnum.SQL_ERROR;

@Slf4j
@Service
public class TeacherHomeworkService {
    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    TeacherHomeworkMapper teacherHomeworkMapper;

    public ResultAPI addHmkBase(HmkTechDTO hmkTechDTO, MultipartFile file, MultipartFile ans_file) {
        //上传
        if (file != null) {
            String url = Upload.upload(file, "homework/");
            hmkTechDTO.setAttachment_url(url);
        }
        if (ans_file != null) {
            String url = Upload.upload(ans_file, "homework/");
            hmkTechDTO.setAnswer_url(url);
        }
        //添加
        boolean flag = teacherHomeworkMapper.addHmkBase(hmkTechDTO);
        if (flag) return ResultAPI.success(hmkTechDTO.getHomework_id());
        return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }

    public ResultAPI updateHmkSetting(HmkTechDTO hmkTechDTO) {
        Boolean isEach = hmkTechDTO.getIs_each();
        HmkTechDTO isExist = teacherHomeworkMapper.isEachExist(hmkTechDTO.getHomework_id());
        teacherHomeworkMapper.updateHmkSetting(hmkTechDTO);
        if (isEach != null && isEach) {
            //如果已经存在互评设置
            if (isExist != null) {
                teacherHomeworkMapper.updateEachHmk(hmkTechDTO);
            } else {
                //进行匿名互评的后端操作：

                teacherHomeworkMapper.insertEachHmk(hmkTechDTO);
            }
        }
        return ResultAPI.success(hmkTechDTO);
    }

    public ResultAPI getHmkList(Integer semesterId) {
        List<HmkTechVO> hmkTechVOList = teacherHomeworkMapper.getHmkList(semesterId);
        return ResultAPI.success(hmkTechVOList);
    }

    /**
     * 获取学生作业完成情况列表（单选筛选）
     *
     * @param homework_id
     * @param is_grade
     * @param submit_status
     * @param division_id
     * @return
     */
    public ResultAPI getHmkGradeList(Integer homework_id, Integer is_grade, Integer submit_status, Integer division_id) {
        List<HmkStuGrade> hmkStuGrades = teacherHomeworkMapper.getHmkGradeList(homework_id, is_grade, submit_status, division_id);
        for (HmkStuGrade item : hmkStuGrades) {
            List<HmkEachGrade> grades = item.getHmk_each_grades();
            List<HmkEachGrade> t_grades = new ArrayList<>();
            List<HmkEachGrade> a_grades = new ArrayList<>();

            Iterator<HmkEachGrade> iterator = grades.iterator();
            while (iterator.hasNext()) {
                HmkEachGrade grade = iterator.next();
                if (grade.getIdentity() == null || grade.getIdentity() == 0) continue;
                if (grade.getIdentity() == 1) {
                    t_grades.add(grade);
                } else if (grade.getIdentity() == 2) {
                    a_grades.add(grade);
                }
                iterator.remove();
            }

            item.setTech_grades(t_grades);
            item.setAdmin_grades(a_grades);
        }
        return ResultAPI.success(hmkStuGrades);
    }

    public ResultAPI getHmkOverview(Integer homeworkId) {
        HmkGradeAll hmkGradeAll = teacherHomeworkMapper.getHmkOverview(homeworkId);
        return ResultAPI.success(hmkGradeAll);
    }

    public ResultAPI getStuHmk(Integer stuHmwkId) {
        HmkStu hmkStu = teacherHomeworkMapper.getStuHmkById(stuHmwkId);
        return ResultAPI.success(hmkStu);
    }

    @Transactional
    public ResultAPI addHmkGrade(HmkStuGradeDTO hmkStuGradeDTO) {
        // 定义事务属性
        TransactionDefinition def = new DefaultTransactionDefinition();
        // 获取事务状态
        TransactionStatus status = transactionManager.getTransaction(def);
        Integer stuHmwkId = hmkStuGradeDTO.getStu_hmwk_id();
        Double techW = 0.0;
        Double adminW = 0.0;
        Double stuW = 0.0;
        try {
            //先添加分数
            teacherHomeworkMapper.addHmkGrade(hmkStuGradeDTO);
            //获取该课堂分值占比以及是否选择学生互评
            HmkTechDTO hmkTechDTO = teacherHomeworkMapper.getHmkWeight(stuHmwkId);
            if (hmkTechDTO.getIs_each()) {
                Double all = hmkTechDTO.getTech_weight() + hmkTechDTO.getAdmin_weight() + hmkTechDTO.getEach_weight();
                techW = (hmkTechDTO.getTech_weight() / all);
                adminW = (hmkTechDTO.getAdmin_weight() / all);
                stuW = (hmkTechDTO.getEach_weight() / all);
            } else {
                Double all = hmkTechDTO.getTech_weight() + hmkTechDTO.getAdmin_weight();
                techW = (hmkTechDTO.getTech_weight() / all);
                adminW = (hmkTechDTO.getAdmin_weight() / all);
            }
            log.info("占比情况" + "学生：" + stuW
                    + "老师" + techW
                    + "管理员" + adminW);
            //获取该作业被评所有身份有效分数的平均分
            List<HmkEachGrade> hmkEachGrade = teacherHomeworkMapper.getStuEachScore(stuHmwkId);
            log.info("三个身份分别平均分" + hmkEachGrade.toString());
            //获取该被评作业的总分（占比系统
            Double getscore = 0.0;
            for (HmkEachGrade item : hmkEachGrade) {
                if (item.getIdentity() == 1) {
                    getscore += item.getEach_score() * techW;
                } else if (item.getIdentity() == 2) {
                    getscore += item.getEach_score() * adminW;
                } else if (hmkTechDTO.getIs_each() && item.getIdentity() == 0) {
                    getscore += item.getEach_score() * stuW;
                    teacherHomeworkMapper.updateEachCnt(hmkStuGradeDTO);
                    teacherHomeworkMapper.updateEachedCnt(stuHmwkId);
                }
            }
            getscore = Math.round(getscore * 100.0) / 100.0;
            //加入getscore中
            teacherHomeworkMapper.updateGetScore(getscore, stuHmwkId);
            // 提交事务
            transactionManager.commit(status);
        } catch (Exception e) {
            // 回滚事务
            transactionManager.rollback(status);
            log.error(e.getMessage());
            return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
        }
        return ResultAPI.success();
    }

    public ResultAPI getHmkSetting(Integer homeworkId) {
        HmkTechDTO hmkTechDTO = teacherHomeworkMapper.getHmkSetting(homeworkId);
        hmkTechDTO.setHomework_id(homeworkId);
        return ResultAPI.success(hmkTechDTO);
    }

    public ResultAPI getGradeCommentList(Integer stuHmwkId) {
        List<HmkGradeComment> hmkGradeComments = teacherHomeworkMapper.getGradeCommentList(stuHmwkId);
        return ResultAPI.success(hmkGradeComments);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultAPI updateGradeByTech(HmkOutRule hmkOutRule) {
        //首先要判断这个人是否在作业表中（如果没交那就是不在了所以需要创建数据）
        Integer stu_hmwk_id = hmkOutRule.getStu_hmwk_id();
        if (stu_hmwk_id == null) {
            teacherHomeworkMapper.insertGradeByTech(hmkOutRule);
        } else {
            try {
                teacherHomeworkMapper.updateGradeByTech(hmkOutRule);
            } catch (Exception e) {
                return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
            }
        }
        //其次要判断时间，到底是按时提交还是补交
        return ResultAPI.success();
    }

    public ResultAPI deleteHmkList(List<Integer> homework_ids) {
        log.info(homework_ids.toString());
        try {
            teacherHomeworkMapper.deleteHmkList(homework_ids);
        } catch (Exception e) {
            log.info(e.toString());
            return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
        }
        return ResultAPI.success();
    }

    public ResultAPI getHmkBase(Integer homeworkId) {
        HmkTechDTO hmkTechDTO;
        try {
            hmkTechDTO = teacherHomeworkMapper.getHmkBase(homeworkId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
        }
        return ResultAPI.success(hmkTechDTO);
    }

    public ResultAPI updateHmkBase(HmkTechDTO hmkTechDTO, MultipartFile file, MultipartFile ans_file) {
        //上传
        if (file != null) {
            String url = Upload.upload(file, "homework/");
            hmkTechDTO.setAttachment_url(url);
        }
        if (ans_file != null) {
            String url = Upload.upload(ans_file, "homework/");
            hmkTechDTO.setAnswer_url(url);
        }
        try {
            teacherHomeworkMapper.updateHmkSetting(hmkTechDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
        }
        return ResultAPI.success();
    }

}
